﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using Serilog;
using System.Collections;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using VideoTools.vo;
namespace VideoTools.service
{

    public interface ITranslate
    {
        public List<string> TranslateText(List<string> inputs, string from, string to);
    }
    public class TranslateGoogle : ITranslate
    {
        public List<string> TranslateText(List<string> inputs, string from, string to)
        {
            string translation = "";
            try
            {
                string input = "";
                for (int i = 0; i < inputs.Count; i++)
                {
                    input += inputs[i];
                }
                string url = String.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}", from, to, Uri.EscapeUriString(input));
                HttpClient httpClient = new HttpClient();
                string result = httpClient.GetStringAsync(url).Result;
                //[[["Daughter Zhen Huan meets the Emperor and Queen Mother","臣女甄嬛参见皇上太后",null,null,3,null,null,[[]],[[["af64405095a399ceb1e05c7abb7cda66","zh_en_2023q1.md"]]]]],null,"zh-CN",null,null,null,null,[]]

                var jsonData = JsonConvert.DeserializeObject<List<dynamic>>(result);
                var translationItems = jsonData[0];
                int count = 0;
                foreach (object item in translationItems)
                {
                    IEnumerable translationLineObject = item as IEnumerable;
                    IEnumerator translationLineString = translationLineObject.GetEnumerator();
                    translationLineString.MoveNext();
                    translation += string.Format(count == 0 ? " {0}" : "{0}", Convert.ToString(translationLineString.Current));
                    count++;
                }
                if (translation.Length > 1) { translation = translation.Substring(1); };
            }
            catch { 
                string message = String.Format("GoogleAPI翻译失败。源语言：{0} 目标语言：{1}", from, to); 
                Log.Error(message);
            }
            List<string> list = new List<string>();
            list.Add(translation);
            return list;
        }
    }

    public class TranslateGoogleBatch : ITranslate
    {
        private HttpClient Client = new HttpClient();
        private string DoRequest(string body)
        {
            var client = new RestClient("https://translate-pa.googleapis.com/v1/translateHtml");
            var rest = new RestRequest();
            rest.Method = Method.Post;
            rest.RequestFormat = DataFormat.Json;
            rest.AddHeader("Host", "translate-pa.googleapis.com");
            rest.AddHeader("Accept-Encoding", "gzip, deflate, br, zstd");
            rest.AddHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
            rest.AddHeader("Content-Type", "application/json+protobuf");
            rest.AddHeader("Origin", "https://translatesubtitles.com");
            rest.AddHeader("Priority", "u=1, i");
            rest.AddHeader("Referer", "https://translatesubtitles.com/");
            rest.AddHeader("Sec-Ch-Ua", "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Microsoft Edge\";v=\"126\"");
            rest.AddHeader("Sec-Ch-Ua-Mobile", "?0");
            rest.AddHeader("Sec-Ch-Ua-Platform", "\"Windows\"");
            rest.AddHeader("Sec-Fetch-Dest", "empty");
            rest.AddHeader("Sec-Fetch-Mode", "cors");
            rest.AddHeader("Sec-Fetch-Site", "cross-site");
            rest.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0");
            rest.AddHeader("X-Goog-Api-Key", "AIzaSyATBXajvzQLTDHEQbcpq0Ihe0vWDHmO520");
            rest.AddParameter("application/json+protobuf",body, ParameterType.RequestBody);
            RestResponse restResp = client.Execute(rest,Method.Post);
            var responseContent = restResp.Content;
            return responseContent;
        }
       
        public List<string> TranslateText(List<string> inputs, string from, string to)
        {
            GooglePayload payload = new GooglePayload();
            payload.targets = inputs;
            payload.language = to;
            DateTime now = DateTime.Now;
            var resp = DoRequest(payload.ToString());
            //Log.Information("翻译耗时" + (DateTime.Now.TimeOfDay.TotalMilliseconds - now.TimeOfDay.TotalMilliseconds));
            var jsonData = JsonConvert.DeserializeObject<List<dynamic>>(resp);
            JArray list = jsonData[0];
            List<string> outputs = new List<string>();
            for (int i = 0; i < list.Count; i++)
            {
                //Log.Information(from + "->" + to + "[" + inputs[i] + "]" + list[i].ToString());
                outputs.Add(list[i].ToString());
            }
            return outputs;
        }
    }

    public class TranslateTencent : ITranslate
    {
        private static readonly HttpClient Client = new HttpClient();
        private string DoRequest(string secretId, string secretKey,string service, string version, string action,string body, string region, string token)
        {
            var request = BuildRequest(secretId, secretKey, service, version, action, body, region, token);
            var response = Client.Send(request);
            return response.Content.ReadAsStringAsync().Result;
        }
        HttpRequestMessage BuildRequest(string secretId, string secretKey,string service, string version, string action,string body, string region, string token)
        {
            var host = "tmt.tencentcloudapi.com";
            var url = "https://" + host;
            string contentType = "application/json; charset=utf-8";
            var timestamp = ((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds).ToString();
            var auth = GetAuth(secretId, secretKey, host, contentType, timestamp, body);
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Post;
            request.Headers.Add("Host", host);
            request.Headers.Add("X-TC-Timestamp", timestamp);
            request.Headers.Add("X-TC-Version", version);
            request.Headers.Add("X-TC-Action", action);
            request.Headers.Add("X-TC-Region", region);
            request.Headers.Add("X-TC-Token", token);
            request.Headers.Add("X-TC-RequestClient", "SDK_NET_BAREBONE");
            request.Headers.TryAddWithoutValidation("Authorization", auth);
            // request.Headers.Authorization = new AuthenticationHeaderValue(auth);
            request.RequestUri = new Uri(url);
            request.Content = new StringContent(body, MediaTypeWithQualityHeaderValue.Parse(contentType));
            Console.WriteLine(request);
            return request;
        }

        static string GetAuth(
            string secretId, string secretKey, string host, string contentType,
            string timestamp, string body
        )
        {
            var canonicalURI = "/";
            var canonicalHeaders = "content-type:" + contentType + "\nhost:" + host + "\n";
            var signedHeaders = "content-type;host";
            var hashedRequestPayload = Sha256Hex(body);
            var canonicalRequest = "POST" + "\n"
                                          + canonicalURI + "\n"
                                          + "\n"
                                          + canonicalHeaders + "\n"
                                          + signedHeaders + "\n"
                                          + hashedRequestPayload;

            var algorithm = "TC3-HMAC-SHA256";
            var date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(int.Parse(timestamp))
                .ToString("yyyy-MM-dd");
            var service = host.Split(".")[0];
            var credentialScope = date + "/" + service + "/" + "tc3_request";
            var hashedCanonicalRequest = Sha256Hex(canonicalRequest);
            var stringToSign = algorithm + "\n"
                                         + timestamp + "\n"
                                         + credentialScope + "\n"
                                         + hashedCanonicalRequest;

            var tc3SecretKey = Encoding.UTF8.GetBytes("TC3" + secretKey);
            var secretDate = HmacSha256(tc3SecretKey, Encoding.UTF8.GetBytes(date));
            var secretService = HmacSha256(secretDate, Encoding.UTF8.GetBytes(service));
            var secretSigning = HmacSha256(secretService, Encoding.UTF8.GetBytes("tc3_request"));
            var signatureBytes = HmacSha256(secretSigning, Encoding.UTF8.GetBytes(stringToSign));
            var signature = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower();

            return algorithm + " "
                             + "Credential=" + secretId + "/" + credentialScope + ", "
                             + "SignedHeaders=" + signedHeaders + ", "
                             + "Signature=" + signature;
        }

        public static string Sha256Hex(string s)
        {
            using (SHA256 algo = SHA256.Create())
            {
                byte[] hashbytes = algo.ComputeHash(Encoding.UTF8.GetBytes(s));
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < hashbytes.Length; ++i)
                {
                    builder.Append(hashbytes[i].ToString("x2"));
                }

                return builder.ToString();
            }
        }

        private static byte[] HmacSha256(byte[] key, byte[] msg)
        {
            using (HMACSHA256 mac = new HMACSHA256(key))
            {
                return mac.ComputeHash(msg);
            }
        }
        public List<string> TranslateText(List<string> inputs, string from, string to)
        {
            var secretId = "AKIDMfwCh7LYdUHrGRO6a9fDdptOyVxaKvSt";
            var secretKey = "ax64rY8WjiaJ2e5Sl6KLdgXBYhhV6Sak";
            var token = "";
            var service = "tmt";
            var version = "2018-03-21";
            var action = "TextTranslate";
            string input = "";
            for (int i = 0; i < inputs.Count; i++)
            {
                input += inputs[i];
            }
            var body = "{\"SourceText\":\""+input+"\",\"Source\":\""+from+"\",\"Target\":\""+to+"\",\"ProjectId\":1313350}";
            var region = "ap-beijing";
            var resp = DoRequest(secretId, secretKey, service, version, action, body, region, token);
            var jsonData = JsonConvert.DeserializeObject<TencentResponse>(resp);
            List<string> list = new List<string>();
            list.Add(jsonData.Response.TargetText);
            return list;
        }
    }
    internal class TencentResponse
    {
        public ResponseObject Response { get; set; }
    }
    internal class ResponseObject
    {
        public string TargetText { get; set; }
        public string Source { get; set; }
        public string Targe { get; set; }
        public string RequestId { get; set; }

    }
    
}
